<?php

function procedure_call_2argsM($pr, $var)
    {  
        require("./Conn.php");
        $array = Array();
        if (!$conn) 
        {
            $m = oci_error();
            trigger_error(htmlentities($m['message']), E_USER_ERROR);
        } 
        $curs = oci_new_cursor($conn);
        $stid = oci_parse($conn, "begin ".$pr."(:cursorAux, '".$var."'); end;");
        oci_bind_by_name($stid, ":cursorAux", $curs, -1, OCI_B_CURSOR);
        oci_execute($stid);
        oci_execute($curs);  // Execute the REF CURSOR like a normal statement id 
        $i =0; 
        while ($row = oci_fetch_array($curs, OCI_ASSOC)) 
        {   
            array_push($array, $row);
        } 
        return $array;
    }

$json = array("success" => false, "msj" => "No se modificó el role");
$role = json_decode(filter_input(INPUT_POST, 'rolem_'));  
if($role != NULL)
{ 
    
    
    
    $role_name = $role[0]; 
    $query_crear = $role[1]; 
    $oldRols = procedure_call_2argsM("ROLESUSUARIO",$role_name); 
    $oldPrivs = procedure_call_2argsM("PRIVILEGIOS",$role_name);  
    $privs = $role[2];
    $roless = $role[3];
//    echo $privs;
//    echo $roless;
    $Run_ = fopen("run2Role.sql", "w+") or die("no abrió run.sql");  
      
    
    $str_run = "";
        foreach ($oldRols as $r)
        { 
            $str_run.="REVOKE ".implode($r)." FROM ".$role_name.";\n";
        }
        foreach ($oldPrivs as $pr)
        { 
            $str_run.="REVOKE ".implode($pr)." FROM ".$role_name.";\n";
        }
        
        $str_run .= $query_crear."\n"; 
    foreach ($privs as $p)
        $str_run.= "GRANT ".$p." TO ".$role_name.";\n";
    foreach ($roless as $r)
        $str_run.= "GRANT ".$r." TO ".$role_name.";\n";
    fwrite($Run_, $str_run); 
    fclose($Run_);
    exec("cmd2_.bat");
    $json['success'] = true;
    $json['msj'] = 'Role '.$role_name.' modificado con exito'; 
}
print( json_encode($json));